package com.flydust.apipulse.controller;

import com.flydust.apipulse.entity.Project;
import com.flydust.apipulse.service.ProjectService;
import com.flydust.apipulse.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@RequestMapping("/api/projects")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class ProjectController {

    private static final Logger logger = Logger.getLogger(ProjectController.class.getName());

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FileUploadService fileUploadService;

    // 获取所有项目
    @GetMapping
    public ResponseEntity<List<Project>> getAllProjects() {
        logger.info("获取所有项目列表");
        try {
            List<Project> projects = projectService.findAllWithEndpointCount();
            return ResponseEntity.ok(projects);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取项目列表时发生异常", e);
            throw e;
        }
    }

    // 根据ID获取项目
    @GetMapping("/{id}")
    public ResponseEntity<Project> getProjectById(@PathVariable Long id) {
        logger.info("根据ID获取项目: " + id);
        try {
            Optional<Project> project = projectService.findById(id);
            if (project.isPresent()) {
                // 设置接口数量
                Project projectWithCount = project.get();
                if (projectWithCount.getEndpoints() != null) {
                    projectWithCount.setEndpointCount(projectWithCount.getEndpoints().size());
                }
                return ResponseEntity.ok(projectWithCount);
            } else {
                logger.warning("未找到ID为 " + id + " 的项目");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取项目详情时发生异常，项目ID: " + id, e);
            throw e;
        }
    }

    // 创建项目
    @PostMapping
    public Project createProject(@RequestBody Project project) {
        logger.info("创建项目: " + project.getName());
        try {
            return projectService.save(project);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "创建项目时发生异常，项目名称: " + project.getName(), e);
            throw e;
        }
    }

    // 更新项目
    @PutMapping("/{id}")
    public ResponseEntity<Project> updateProject(@PathVariable Long id, @RequestBody Project projectDetails) {
        logger.info("更新项目: " + id);
        try {
            Optional<Project> project = projectService.findById(id);
            if (project.isPresent()) {
                Project updatedProject = project.get();
                updatedProject.setName(projectDetails.getName());
                updatedProject.setDescription(projectDetails.getDescription());
                updatedProject.setIconUrl(projectDetails.getIconUrl());
                Project savedProject = projectService.save(updatedProject);
                return ResponseEntity.ok(savedProject);
            } else {
                logger.warning("未找到ID为 " + id + " 的项目进行更新");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "更新项目时发生异常，项目ID: " + id, e);
            throw e;
        }
    }

    // 删除项目
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProject(@PathVariable Long id) {
        logger.info("删除项目: " + id);
        try {
            Optional<Project> project = projectService.findById(id);
            if (project.isPresent()) {
                projectService.deleteById(id);
                return ResponseEntity.noContent().build();
            } else {
                logger.warning("未找到ID为 " + id + " 的项目进行删除");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "删除项目时发生异常，项目ID: " + id, e);
            throw e;
        }
    }
    
    // 上传项目图标
    @PostMapping("/{id}/icon")
    public ResponseEntity<String> uploadProjectIcon(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        logger.info("上传项目图标，项目ID: " + id);
        try {
            // 检查项目是否存在
            Optional<Project> project = projectService.findById(id);
            if (project.isPresent()) {
                // 上传文件到七牛云并获取URL
                String fileUrl = fileUploadService.uploadFile(file);
                
                // 更新项目图标URL
                Project updatedProject = project.get();
                updatedProject.setIconUrl(fileUrl);
                projectService.save(updatedProject);
                
                logger.info("项目图标上传成功，项目ID: " + id + ", 图标URL: " + fileUrl);
                return ResponseEntity.ok(fileUrl);
            } else {
                logger.warning("未找到ID为 " + id + " 的项目进行图标更新");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "上传项目图标时发生异常，项目ID: " + id, e);
            return ResponseEntity.status(500).body("上传失败: " + e.getMessage());
        }
    }
}